// 精灵系统 - 管理游戏图像资源
class Sprite {
    constructor(image, frameWidth, frameHeight, frameCount = 1) {
        this.image = image;
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.frameCount = frameCount;
        this.currentFrame = 0;
        this.animationSpeed = 0.1;
        this.animationTimer = 0;
        this.loop = true;
    }
    
    update(deltaTime) {
        if (this.frameCount > 1) {
            this.animationTimer += deltaTime;
            if (this.animationTimer >= this.animationSpeed) {
                this.animationTimer = 0;
                this.currentFrame++;
                if (this.currentFrame >= this.frameCount) {
                    if (this.loop) {
                        this.currentFrame = 0;
                    } else {
                        this.currentFrame = this.frameCount - 1;
                    }
                }
            }
        }
    }
    
    render(ctx, x, y, width = null, height = null) {
        const drawWidth = width || this.frameWidth;
        const drawHeight = height || this.frameHeight;
        
        ctx.drawImage(
            this.image,
            this.currentFrame * this.frameWidth, 0,
            this.frameWidth, this.frameHeight,
            x - drawWidth / 2, y - drawHeight / 2,
            drawWidth, drawHeight
        );
    }
    
    setAnimationSpeed(speed) {
        this.animationSpeed = speed;
    }
    
    setLoop(loop) {
        this.loop = loop;
    }
}

// 精灵管理器
class SpriteManager {
    constructor() {
        this.sprites = new Map();
        this.images = new Map();
        this.loadedCount = 0;
        this.totalCount = 0;
    }
    
    // 加载图像
    loadImage(key, src) {
        return new Promise((resolve, reject) => {
            this.totalCount++;
            const img = new Image();
            img.onload = () => {
                this.images.set(key, img);
                this.loadedCount++;
                resolve(img);
            };
            img.onerror = () => {
                reject(new Error(`Failed to load image: ${src}`));
            };
            img.src = src;
        });
    }
    
    // 创建精灵
    createSprite(key, frameWidth, frameHeight, frameCount = 1) {
        const image = this.images.get(key);
        if (!image) {
            console.error(`Image not found: ${key}`);
            return null;
        }
        
        const sprite = new Sprite(image, frameWidth, frameHeight, frameCount);
        this.sprites.set(key, sprite);
        return sprite;
    }
    
    // 获取精灵
    getSprite(key) {
        return this.sprites.get(key);
    }
    
    // 批量加载图像
    async loadImages(imageList) {
        this.totalCount = imageList.length;
        this.loadedCount = 0;
        
        const promises = imageList.map(async (imageInfo) => {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    this.images.set(imageInfo.key, img);
                    this.loadedCount++;
                    console.log(`✓ Loaded image: ${imageInfo.key} (${this.loadedCount}/${this.totalCount})`);
                    resolve();
                };
                img.onerror = (error) => {
                    console.error(`✗ Failed to load image ${imageInfo.src}:`, error);
                    console.log('Current page URL:', window.location.href);
                    console.log('Attempted image path:', imageInfo.src);
                    // 不拒绝Promise，而是继续执行，这样其他图片仍能加载
                    resolve();
                };
                img.src = imageInfo.src;
            });
        });

        await Promise.all(promises);
        console.log('Image loading completed. Loaded images:', Array.from(this.images.keys()));
    }
    
    // 获取加载进度
    getLoadingProgress() {
        return this.totalCount > 0 ? this.loadedCount / this.totalCount : 1;
    }
    
    // 是否加载完成
    isLoaded() {
        return this.loadedCount === this.totalCount;
    }
}

// 粒子系统
class Particle {
    constructor(x, y, vx, vy, life, color, size) {
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.life = life;
        this.maxLife = life;
        this.color = color;
        this.size = size;
        this.alpha = 1;
    }
    
    update(deltaTime) {
        this.x += this.vx * deltaTime;
        this.y += this.vy * deltaTime;
        this.life -= deltaTime;
        this.alpha = this.life / this.maxLife;
        
        return this.life > 0;
    }
    
    render(ctx) {
        ctx.save();
        ctx.globalAlpha = this.alpha;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    }
}

class ParticleSystem {
    constructor() {
        this.particles = [];
    }
    
    addParticle(x, y, vx, vy, life, color, size) {
        this.particles.push(new Particle(x, y, vx, vy, life, color, size));
    }
    
    addExplosion(x, y, color = '#ff4444', count = 10) {
        for (let i = 0; i < count; i++) {
            const angle = (Math.PI * 2 * i) / count;
            const speed = 50 + Math.random() * 100;
            const vx = Math.cos(angle) * speed;
            const vy = Math.sin(angle) * speed;
            const life = 500 + Math.random() * 500;
            const size = 2 + Math.random() * 3;
            
            this.addParticle(x, y, vx, vy, life, color, size);
        }
    }
    
    addTrail(x, y, color = '#ffff00') {
        const vx = (Math.random() - 0.5) * 20;
        const vy = (Math.random() - 0.5) * 20;
        const life = 200 + Math.random() * 300;
        const size = 1 + Math.random() * 2;
        
        this.addParticle(x, y, vx, vy, life, color, size);
    }
    
    update(deltaTime) {
        this.particles = this.particles.filter(particle => 
            particle.update(deltaTime)
        );
    }
    
    render(ctx) {
        this.particles.forEach(particle => particle.render(ctx));
    }
}

// 全局精灵管理器实例
window.spriteManager = new SpriteManager();
window.particleSystem = new ParticleSystem(); 